package castle.defense.project;

import java.util.ArrayList;

import android.graphics.Canvas;
import android.view.SurfaceHolder;

/**
 * The thread that runs the menu screen.
 * 
 * @author Daniel Wasserman
 *
 */
public class HighscoreThread extends Thread {
	private SurfaceHolder sholder;
	private boolean running, paused, started;
	private ArrayList<SoftButton> buttons;
	/**
	 * @param c The context this thread is in.
	 * 
	 * The main thread to run the Menu Screen.
	 */
	public HighscoreThread() {
		started = false;
		paused = true;
		running = false;
	}

	public void initializeButtons() {
		buttons = new ArrayList<SoftButton>();
		int[] highscores = Options.highscores;
		double buffer = 5;
		double height = 10;
		double topmargin = 20;
		for(int i = 0; i < highscores.length; i++) {
			buttons.add(new SoftButton(PE.regionByPercent(25,100-(topmargin+(height+buffer)*i),50,height)));
			buttons.get(i).setTextOne(String.format("%d: %d", i+1,highscores[i]));
		}
	}

	/**
	 * 
	 * @param h The surface holder for the thread
	 * 
	 * The surface holder allows the program to get the canvas to draw things.
	 */
	public void setSurfaceHolder(SurfaceHolder h) {
		this.sholder = h;
	}
	/**
	 * @param r Set whether the program should start running or stop.
	 */
	public void setRunning(boolean r) {running = r;}
	/**
	 * @param p Whether or not to pause the thread
	 */
	public void setPaused(boolean p) {paused = p;}

	/**
	 * Function to start the thread running.
	 */
	public void start()
	{
		if(!started)
		{
			started = true;
			setPaused(false);
			setRunning(true);
			initializeButtons();
			super.start();
		}
	}
	/**
	 * Pretty self explanatory.
	 */
	public void run() {
		while(running)
		{
			if(!paused)
			{
				long curTime = System.currentTimeMillis();
				Canvas c = null;
				try {
					c = sholder.lockCanvas();
					synchronized(sholder) {
						doDraw(c);
					}
				} finally {
					if(c!=null)
						sholder.unlockCanvasAndPost(c);
				}
			}
			else
			{

			}
		}
	}
	/**
	 * @param c The canvas to be drawn on.
	 * 
	 * This function tells all objects in the menu to draw themselves on the screen.
	 */
	public void doDraw(Canvas c) {
		GraphicsEngine.drawBackground(c);
		//draw scores
		for(SoftButton b : buttons) {
			b.draw(c);
		}
		GraphicsEngine.drawText(c, "Highscores", PE.screenPercentX(50), PE.screenPercentY(10), 10);
	}
}
